import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/api_response.dart';
import '../models/user.dart';
import '../utils/token_manager.dart';
import 'moment_service.dart';

class AuthService {
  Future<User> login(String username, String password) async {
    try {
      final url = Uri.parse('${MomentService.baseUrl}/user/login');

      print('=== login ===');
      print('URL: $url');
      print('Request Body: ${json.encode({'username': username, 'password': password})}');

      final response = await http.post(
        url,
        headers: {
          'Content-Type': 'application/json',
        },
        body: json.encode({
          'username': username,
          'password': password,
        }),
      );

      print('Status Code: ${response.statusCode}');
      print('Response Body: ${utf8.decode(response.bodyBytes)}');

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse<User>.fromJson(
          jsonData,
          (data) => User.fromJson(data as Map<String, dynamic>),
        );

        if (apiResponse.isSuccess && apiResponse.data != null) {
          // 保存用户信息和token
          await TokenManager.saveUser(apiResponse.data!);
          return apiResponse.data!;
        } else {
          throw Exception(apiResponse.message);
        }
      } else {
        throw Exception('登录失败: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('登录失败: $e');
    }
  }

  Future<void> logout() async {
    await TokenManager.clearUser();
  }
}
